﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.IO;
using System.IO.Ports;
using System.Windows.Forms;
using System.Data;
using System.Xml;
using IniFile;
using System.Globalization;
using FlightSys.FsFsdb;

namespace FsDump
{
    public class MainClass
    {
        public static bool UseIdNotRegistered = true;
        public static decimal Interfaces = 0;
        public static decimal InterfacesO = 0;
        public static decimal Utcdiff = -3;
        public static decimal Mode = 1;
        public static bool Usefilter = false;
        public static bool Poff = false;
        public static bool UseCustomID = false;
        public static string CustomID = string.Empty;
        public static string GpsDumpPath = string.Empty;
        public static string FsdbPath = string.Empty;
        public static string TnpPath = string.Empty;
        public static string FlightsPath = string.Empty;
        public static DateTime FilterTime = DateTime.Now;
        public static string ClassName;
        public static Fsdb Fs ;
        public static IniFileReader ifr = new IniFile.IniFileReader(Application.StartupPath + @"\Fsdump.ini", true);
        public static void ReadConfig()
        {            
            GpsDumpPath = ifr.GetIniValue("Settings", "GpsDumpPath");
            FsdbPath = ifr.GetIniValue("Settings", "FsdbPath");
            TnpPath = ifr.GetIniValue("Settings", "TnpPath");
            FlightsPath = ifr.GetIniValue("Settings", "FlightsPath");
            Mode = Convert.ToInt16(ifr.GetIniValue("Settings", "Mode"));
            Interfaces = Convert.ToDecimal(ifr.GetIniValue("Settings", "Interfaces"));
            Usefilter = Convert.ToBoolean(ifr.GetIniValue("Settings", "Usefilter"));
            FilterTime = Convert.ToDateTime(ifr.GetIniValue("Settings", "FilterTime"));//.ToString("dd/MM/yyyy HH:mm:ss") 
            Utcdiff = Convert.ToDecimal(ifr.GetIniValue("Settings", "Utcdiff"));
            Poff = Convert.ToBoolean(ifr.GetIniValue("Settings", "Poff"));
            UseCustomID = Convert.ToBoolean(ifr.GetIniValue("Settings", "UseCustomID"));
            CustomID = ifr.GetIniValue("Settings", "CustomID");


        }
        public static void SaveConfig()
        {
            if (ifr != null)
            {
                ifr.OutputFilename = ifr.IniFilename;
                ifr.Save();
            }
        }
        public static void SetPortNameValues(object obj)
        {
            int i = 0;
            ((ComboBox)obj).Items.Add("/usb");
            foreach (string str in SerialPort.GetPortNames())
            {

                ((ComboBox)obj).Items.Add(str.Replace("COM", " /com="));
                i += 1;
            }
        }
        public static void SetGpsNames(object obj)
        {
            string[] gpsN = { "Garmin", "All Brauniger and Flytec", "Log_It/MuzzyLogger/Tracklogger", "Top Navigator", "XC Trainer", "XC Trainer MXP", "MLR", "Digifly Leonardo", "Digifly Graviter", "Magellan", "Flymaster", "DSX" };
            foreach (string str in gpsN)
            {
                ((ComboBox)obj).Items.Add(str);
            }
        }
        public static string GetGpsNames(int i)
        {
            string[] gps = { " /gps=garmin", " /gps=iqcompeo", " /gps=logit", " /gps=topnav", " /gps=xctrainer", " /gps=xct_mxp", " /gps=mlr", " /gps=mlr", " /gps=graviter", " /gps=magellan", " /gps=flymaster" , " /gps=dsx"};
            return gps[i];
        }
        public static bool IsNumeric(string anyString)
        {
            if (anyString == null)
            {
                anyString = "";
            }
            if (anyString.Length > 0)
            {
                double dummyOut = new double();
                System.Globalization.CultureInfo cultureInfo = new System.Globalization.CultureInfo("en-US", true);
                return Double.TryParse(anyString, System.Globalization.NumberStyles.Any, cultureInfo.NumberFormat, out dummyOut);
            }
            else
            {
                return false;
            }
        }
        public static string DMStoDD(string DMS)
         {
             NumberFormatInfo provider = new NumberFormatInfo();
             provider.NumberDecimalSeparator = ".";
             provider.NumberGroupSeparator = ",";
             string IDMS = Convert.ToDouble(DMS).ToString().PadLeft(6, '0');
             string S, M, D;
             S = IDMS[5].ToString();
             M = IDMS[4].ToString();
             D = IDMS[3].ToString();
             double Seconds = Convert.ToDouble(S) / 3600;
             double Minutes = Convert.ToDouble(M) / 60;
             double Degrees = Convert.ToDouble(D);
             double DD = Math.Round ((Seconds + Minutes + Degrees),6);
             return DD.ToString(provider);
         }
        public static string DegToDMS(string Degrees)
        {
            NumberFormatInfo provider = new NumberFormatInfo();
            provider.NumberDecimalSeparator = ".";
            provider.NumberGroupSeparator = ",";
            double L = Convert.ToDouble(Degrees, provider);
            int D = (int)(L);
            L = (L - D) * 60;
            int M = (int)(L);
            var S = Math.Round((L - M) * 60);
            if (Math.Round((L - M) * 60) == 60)
            {
                M = M + 1;
                S = 0;
            }
            return D.ToString() + M.ToString() + S.ToString();
        }
        public static string[] redim(string[] src, int count)
    {
        if(src == null) return new string[count];
        string[] tmp = new string[count];
        src.CopyTo(tmp, 0);
        return tmp;
   }


        public static string[] SearchForCOMPIDonDB(string COMPID)
        {
            string[] toreturn = {COMPID, "", "" };
            try
            {
                Dictionary<string, string> D = Fs.Competition_Participant_Get_attributes(int.Parse(COMPID));

                toreturn[0] =COMPID;
                toreturn[1] =D["CIVLID"];
                toreturn[2] =D["name"];
                return toreturn;
            }
            catch
            {
                return toreturn;
            }

            
        }  
        public static bool CheckIDonDB(string COMPID){
            
            bool toreturn = false;
            string[] Pilots = Fs.Competition_Participants_Get_ids();
            foreach (string id in Pilots)
            {
                if (id == COMPID)
                {
                    toreturn= true;
                    break;
                    
                }
            }
            return toreturn;
        }
        public static int InArray(string[] needles,string[] haystack)
        {
            //Set index to a default negative value (no needle in haystack)
            int index = -1;
            //Foreach needle, search the haystack, if found break
            //the loop and return the index
            foreach (string needle in needles)
            {
                index = Array.BinarySearch(haystack, needle);
                if (index >= 0)
                {
                    break;
                }
            }
            return index;
        }
        public static string[] SearchOnWaypoints(string what, string where, int gpskind) {
            string who = string.Empty;
            string[] founded ={};
            if (File.Exists(where)) 
            {
                string[] lines = File.ReadAllLines(where);
                
                foreach (string line in lines)
                {
                    string[] o = line.Split(',');

                    if (o.Length == 15)
                    {
                        if (gpskind == 1)
                        {
                            if (o[10].Trim() == what)
                            {
                                
                                who = Convert.ToDouble(MainClass.DegToDMS(o[3].Trim()) + MainClass.DegToDMS(o[2].Trim())).ToString();
                                founded = redim(founded, founded.Length + 1);
                                founded[founded.Length-1] = who;
                                //break;
                            }
                        }
                        else {
                            if (o[1].Trim() == what)
                            {
                                who = Convert.ToDouble(MainClass.DegToDMS(o[3].Trim()) + MainClass.DegToDMS(o[2].Trim())).ToString();
                                founded=redim(founded, founded.Length+1);
                                founded[founded.Length-1] = who;
                                // break;
                            }
                        
                        }

                    }
                }
            }
            return founded;
        }
        public static bool wasdownloaded(string COMPID)
        {
            foreach (string entry in Directory.GetFiles(MainClass.FlightsPath, "*.kml"))
            {
                string[] file = entry.Split('.');
                if (file[file.Length - 2] == COMPID)
                {
                    return true;
                }
            }
            return false;
        }
    }
}
